﻿namespace CloudNinja.Metering.Common.Configuration
{
    using System.Configuration;

    public static class ConfigurationElementExtension
    {
        public static string GetCurrentValueOrDefault(this ConfigurationElement configurationElement, string currentValue)
        {
            // All of the database connection strings contain a =
            if ((currentValue.Contains("=") && currentValue.ToLower().Contains("server"))
                || (currentValue.Contains("UseDevelopmentStorage") || currentValue.Contains("AccountName")))
            {
                return currentValue;
            }

            var configuration = configurationElement.CurrentConfiguration;

            var meteringConfig = configuration.Sections["MeteringConfiguration"] as MeteringSection;

            if (meteringConfig == null)
            {
                throw new ConfigurationErrorsException(
                    "Metering configuration is not named as MeteringConfiguration or no Metering configuration is found.");
            }

            var connStr = meteringConfig.CommonSettings.ConnectionStrings.Get(currentValue);

            if (connStr != null)
            {
                var commonConnStr = connStr.Value;

                return commonConnStr;
            }

            throw new ConfigurationErrorsException(
                string.Format(
                    "Metering configuration section does not include a common connection string element with name {0}",
                    currentValue));
        }
    }
}
